package juc_learn;
/**
 * syn-notifyAll-wait实现
 * 生产一个，消费一个
 * 
 *
 */
public class ProdConsumerDemo_syn {
    private int num = 0;
    //生产者
    synchronized public void produce(){
    	while(num!=0){
    		try{
    			//禁止生产
    			wait();
    		}catch(Exception e){
    			e.printStackTrace();
    		}
    	}
    	num++;
    	System.out.println(Thread.currentThread().getName()+":"+num);
    	//返回通知其他所有阻塞的生产者线程、
    	this.notifyAll();
    }
    
    //消费者
    synchronized public void consume(){
    	while(num==0){
    		try{
    			//禁止消费
    			wait();
    		}catch(Exception e){
    			e.printStackTrace();
    		}
    	}
    	//开始消费
    	num--;
    	System.out.println(Thread.currentThread().getName()+":"+num);
    	this.notifyAll();
    	
    }
	public static void main(String[] args) {
		// TODO Auto-generated method stub
        //两个生产者，两个消费者
		ProdConsumerDemo_syn p1 = new ProdConsumerDemo_syn();
		new Thread(()->{
			for(int i=0;i<5;i++){
			 try {
				Thread.sleep(100);
				p1.produce();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			}
			
		},"AA").start();
		
		new Thread(()->{
			for(int i=0;i<5;i++){
				 try {
					Thread.sleep(100);
					p1.consume();
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				}
				
		},"BB").start();
		
		new Thread(()->{
			for(int i=0;i<5;i++){
				 try {
					Thread.sleep(100);
					p1.produce();
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}	
		},"CC").start();
		
		
		new Thread(()->{
			for(int i=0;i<5;i++){
				 try {
					Thread.sleep(100);
					p1.consume();
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}	
		},"DD").start();
		
		
	}

}
